// src/pages/StockKline/StockKlineChart.jsx

import React, { useEffect, useRef, useState } from 'react';
import * as echarts from 'echarts';
import { Card, Input, Select, Spin, message, Badge } from 'antd';
import { useLocation } from 'react-router-dom';
import { $fetchStockKline, $fetchAStockMinute } from '../../api/stockApi';
import {
  StockOutlined,
  SearchOutlined,
  LineChartOutlined,
} from '@ant-design/icons';
import './StockKline.scss';

const { Search } = Input;
const { Option } = Select;

const StockKlineChart = () => {
  const chartRef = useRef(null);
  const location = useLocation(); // 获取当前 URL 信息
  // 默认股票代码为空
  const [symbol, setSymbol] = useState('');
  // 默认日K
  const [period, setPeriod] = useState('1d');
  const [loading, setLoading] = useState(false);

  // 1. 从 URL 参数中获取 symbol
  useEffect(() => {
    const query = new URLSearchParams(location.search);
    const initialSymbol = query.get('symbol') || 'sh600000';
    setSymbol(initialSymbol);
  }, [location.search]);

  // 2. 当 symbol 或 period 改变时，拉取数据并重绘
  useEffect(() => {
    const chart = echarts.init(chartRef.current);

    const load = async () => {
      if (!symbol) return;
      setLoading(true);
      chart.showLoading();

      try {
        let data, times, kLines, vols;

        if (['1', '5', '15', '30', '60'].includes(period)) {
          // 加载分时图数据
          data = await $fetchAStockMinute({ symbol, period });
          times = data.map((d) => d.time);
          kLines = data.map((d) => d.close); // 分时图只绘制收盘价折线
          vols = data.map((d) => d.volume);
        } else {
          // 加载 K 线图数据
          data = await $fetchStockKline(symbol, period);
          times = data.map((d) => d.time);
          kLines = data.map((d) => [d.open, d.close, d.low, d.high]);
          vols = data.map((d) => d.volume);
        }

        chart.hideLoading();

        // 渐变填充折线下方
        const lineGradient = new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(24, 144, 255, 0.4)' },
          { offset: 1, color: 'rgba(24, 144, 255, 0.05)' },
        ]);

        chart.setOption({
          title: {
            text: `${symbol} ${period === '1d' || period === '1w' || period === '1M' ? period.toUpperCase() + ' K线图' : period + ' 分时图'}`,
            left: 'center',
            textStyle: { fontSize: 16 },
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: { type: 'cross' },
            formatter: (params) => {
              if (['1', '5', '15', '30', '60'].includes(period)) {
                // 分时图的 tooltip
                const price = params[0]?.data;
                const volume = params[1]?.data;
                return (
                  `时间：${params[0]?.axisValue}<br/>收盘价：${price}<br/>成交量：${volume}`
                );
              } else {
                // K 线图的 tooltip
                const k = params.find((p) => p.seriesType === 'candlestick');
                if (!k) return '';
                const [op, cl, lo, hi] = k.data;
                return (
                  `时间：${k.axisValue}<br/>开盘：${op}<br/>收盘：${cl}<br/>最低：${lo}<br/>最高：${hi}`
                );
              }
            },
          },
          legend: {
            top: 30,
            data: ['价格', '成交量'],
          },
          grid: [
            { left: '10%', right: '8%', height: '60%' },
            { left: '10%', right: '8%', top: '75%', height: '15%' },
          ],
          xAxis: [
            {
              type: 'category',
              data: times,
              scale: true,
              boundaryGap: false,
              axisLine: { lineStyle: { color: '#888' } },
              axisTick: { show: false },
            },
            {
              type: 'category',
              gridIndex: 1,
              data: times,
              scale: true,
              boundaryGap: false,
              axisTick: { show: false },
              splitLine: { show: false },
              axisLabel: { show: false },
            },
          ],
          yAxis: [
            {
              scale: true,
              splitArea: { show: true },
              axisLine: { lineStyle: { color: '#888' } },
            },
            {
              gridIndex: 1,
              scale: true,
              splitNumber: 2,
              axisLabel: { show: true },
              axisLine: { lineStyle: { color: '#888' } },
            },
          ],
          dataZoom: [
            { type: 'inside', xAxisIndex: [0, 1], start: 50, end: 100 },
            {
              show: true,
              xAxisIndex: [0, 1],
              type: 'slider',
              top: '90%',
              start: 50,
              end: 100,
              backgroundColor: 'rgba(255,255,255,0.1)',
              borderColor: '#ccc',
            },
          ],
          series: [
            {
              name: '价格',
              type: ['1', '5', '15', '30', '60'].includes(period) ? 'line' : 'candlestick',
              data: kLines,
              smooth: true,
              showSymbol: false,
              lineStyle: {
                width: 2,
                color: '#1890ff',
              },
              areaStyle: ['1', '5', '15', '30', '60'].includes(period)
                ? { color: lineGradient }
                : null,
              itemStyle: {
                color: '#f55656',
                color0: '#61a0a8',
                borderColor: '#f55656',
                borderColor0: '#61a0a8',
              },
            },
            {
              name: '成交量',
              type: 'bar',
              xAxisIndex: 1,
              yAxisIndex: 1,
              data: vols,
              barWidth: '60%',
              itemStyle: {
                color: 'rgba(24,144,255,0.6)',
              },
            },
          ],
        });
      } catch (e) {
        chart.hideLoading();
        console.error('数据加载失败', e);
        message.error(e.message || '获取数据失败');
      } finally {
        setLoading(false);
      }
    };

    load();
    const onResize = () => chart.resize();
    window.addEventListener('resize', onResize);
    return () => {
      window.removeEventListener('resize', onResize);
      chart.dispose();
    };
  }, [symbol, period]);

  return (
    <div className="stock-kline-page">
      <div className="kline-header">
        <div className="header-content">
          <div className="header-title">
            <StockOutlined className="header-icon" />
            <h1>股票 K 线 / 分时 图</h1>
            {symbol && <Badge count={symbol} className="symbol-badge" />}
          </div>
          <div className="search-wrapper">
            <Search
              placeholder="输入股票代码，例如：sh600000"
              allowClear
              enterButton={<SearchOutlined />}
              onSearch={(val) => {
                const v = val.trim();
                if (!v) {
                  message.warning('请输入股票代码');
                  return;
                }
                setSymbol(v);
              }}
              className="search-input"
              size="large"
            />
            <Select value={period} className="period-select" onChange={setPeriod} size="large">
              <Option value="1">1 分钟</Option>
              <Option value="5">5 分钟</Option>
              <Option value="15">15 分钟</Option>
              <Option value="30">30 分钟</Option>
              <Option value="60">60 分钟</Option>
              <Option value="1d">日K</Option>
              <Option value="1w">周K</Option>
              <Option value="1M">月K</Option>
            </Select>
          </div>
        </div>
      </div>

      <Card className="kline-card" bordered={false}>
        <Spin spinning={loading} className="spin-center" tip="加载中...">
          <div ref={chartRef} className="chart-container" />
        </Spin>
      </Card>
    </div>
  );
};

export default StockKlineChart;
